package jwt

import (
	com "go-http/netdisk/common"
	"go-http/netdisk/pkg/e"
	"go-http/netdisk/pkg/utils"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func Authorize(c *gin.Context) {

	data := com.ResponseData{Code: e.SUCCESS}

	tokenString := c.GetHeader("Authorization")
	if tokenString == "" {
		data.Code = e.ERROR_AUTH
	} else {
		claims, err := utils.ParseToken(tokenString)
		if err != nil {
			data.Code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
		} else {
			if time.Now().Unix() > claims.ExpiresAt {
				data.Code = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
			} else {
				// fmt.Printf("authorize, uid:%s\n", claims.Uid)
				c.Set("uid", claims.Uid) // 用c.Keys["uid"]取之
			}
		}
	}

	if data.Code == e.SUCCESS {
		c.Next()
	} else {
		data.Msg = e.GetMsg(data.Code)
		c.JSON(http.StatusUnauthorized, data)
		c.Abort()
	}
}
